<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片试图区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" clearable @clear="getUserList" v-model="queryInfo.query">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="1">
          <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表单 -->
      <el-table :data="quertList" stripe border>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="changeState(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <!-- {{scope.row}} -->
            <el-tooltip class="item" effect="dark" content="编辑" placement="top" :enterable="false">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="showEditDialog(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除" placement="top" :enterable="false">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="deleteUser(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="更换状态"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="editStatus(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <!--size-change-pageSize 改变时会触发 每页条数 -->
      <!--current-change currentPage 改变时会触发 页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- dialog对话框 -->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="30%" @close="dialogClosed">
      <!-- nrir主题区域  -->
      <el-form
        :model="addForm"
        :rules="addrules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item v-show="1" label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改 -->
    <el-dialog
      title="添加用户"
      :visible.sync="showEditDialogVisible"
      width="30%"
      @close="showEditDialogClosed"
    >
      <!-- nrir主题区域  -->
      <el-form
        :model="editForm"
        :rules="addrules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input disabled v-model="editForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="showEditDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
    <!--  -->
    <el-dialog title="提示" :visible.sync="setRoleDialogVisible" width="30%" @close='setRoleDialogClose'>
      <div>
        <p class="fleft">当前的用户:{{newList.username}}</p>
        <p class="fleft">当前的角色:{{newList.role_name}}</p>
        <!-- 选择器 --> 
        <el-select v-model="selsectIds" placeholder="请选择">
          <el-option
            v-for="item in getRoles"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"

          ></el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click=" saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>





<script>
import { async } from 'q'
export default {
  data() {
    // 邮箱验证
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^\w+@\w+(\.\w+)+$/
      if (regEmail.test(value)) {
        return cb()
      }
      //返回一个错误提示
      cb(new Error('请输入合法的邮箱'))
    }
    // 手机号
    //验证手机号码的规则
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^1[34578]\d{9}$/
      if (regMobile.test(value)) {
        return cb()
      }
      //返回一个错误提示
      cb(new Error('请输入合法的手机号码'))
    }
    return {
      dialogVisible: false,
      showEditDialogVisible: false,
      queryInfo: {
        query: '',
        // 每条页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 2
      },
      quertList: [],
      total: 0,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
        // 修改数据
      },
       // 获取selct的id
      selsectIds:'',
      // 获取所有的列表
      getRoles:[],
      setRoleDialogVisible: false,
      // 当前列表
      newList: {},
      editForm: {},
      addrules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            validator: checkEmail,
            message: '邮箱格式不正确，请重新输入',
            trigger: 'blur'
          }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            validator: checkMobile,
            message: '手机号码不正确，请重新输入',
            trigger: 'blur'
          }
        ]
      }
   
    }
  },
  methods: {
    async getUserList() {
      const { data: data } = await this.$http.get('/users', {
        params: this.queryInfo
      })
      // console.log(data)

      if (data.meta.status !== 200) return this.$message.error(data.meta.msg)
      console.log(2)

      this.$message.success(data.meta.msg)
      this.quertList = data.data.users
      this.total = data.data.total
      // console.log(this.quertList);
      
    },
    handleSizeChange(newsize) {
      this.queryInfo.pagesize = newsize
      this.getUserList()
    },
    handleCurrentChange(newcurrent) {
      this.queryInfo.pagenum = newcurrent
      this.getUserList()
    },
    async changeState(data) {
      console.log(data)
      const datas = await this.$http.put(
        `users/${data.id}/state/${data.mg_state}`
      )
      console.log(datas)

      if (datas.data.meta.status !== 200) {
        this.$message.error(datas.data.meta.msg)
        datas.data.mg_state = !datas.data.mg_state
      }
      this.$message.success(datas.data.meta.msg)
    },
    dialogClosed() {
      this.$refs.ruleForm.resetFields()
    },
    // 添加
    addUser() {
      this.$refs.ruleForm.validate(async valid => {
        console.log(valid)
        if (!valid) return
        // 添加网络请求
        const { data: res } = await this.$http.post('/users', this.addForm)
        console.log(res)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.dialogVisible = false
        this.$refs.ruleForm.resetFields()
        this.getUserList()
        this.$message.success(res.meta.msg)
      })
    },
    // 展示编辑用户对话框
    async showEditDialog(id) {
      this.showEditDialogVisible = true
      // console.log(id);
      const { data: res } = await this.$http.get('/users/' + id)
      console.log(res)
      this.editForm = res.data
    },
    showEditDialogClosed() {
      this.$refs.ruleForm.resetFields()
    },
    // 修改
    editUser() {
      this.$refs.ruleForm.validate(async vali => {
        console.log(vali)
        if (!vali) return this.$message.error('错误信息')
        const { data: res } = await this.$http.put(
          '/users/' + this.editForm.id,
          {
            id: this.editForm.id,
            email: this.editForm.email,
            mobile: this.editForm.mobile
          }
        )
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getUserList()
        this.showEditDialogVisible = false
      })
    },
    // 删除
    async deleteUser(id) {
      const val = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(ret => ret)
      if (val != 'confirm') return this.$message.info('取消删除')
      const { data: res } = await this.$http.delete('/users/' + id)
      this.$message.success('删除成功')
      this.getUserList()
    },
    async editStatus(val) {
      this.newList = val
      // console.log(val);
      // 获取所有的角色列表     
      const {data:res} = await this.$http.get('/roles')
      console.log(res);
      this.getRoles = res.data
      this.setRoleDialogVisible = true
    },
    // 点击按钮 分配角色
    async saveRoleInfo (){
      if(!this.selsectIds) return this.$message.error('请选择角色')
      const {data:res} =await this.$http.put(`users/${this.newList.id}/role`,
      {rid:this.selsectIds})
      console.log(res);
      if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.getUserList()
      this.setRoleDialogVisible = false
    },
    setRoleDialogClose(){
      this.selsectIds = ''
       
    }
  },

  created() {
    this.getUserList()
  }
}
</script>
<style lang='css' scoped>
.el-button {
  text-align: left;
}
.fleft {
  text-align: left;
}
</style>
